<template>
  <div class="commodity_manage">
    <search-table :url="url" ref="searchtable" :columns="columns"
                  :pagination="pagination" :form="form">
      <template slot="searchForm">
        <a-form layout="inline" :form="form">
          <a-form-item label="商品名称">
            <a-input
              style="width:180px"
              v-decorator="[
                'goodsName',
              ]"
              placeholder="请输入商品名称"
            >
            </a-input>
          </a-form-item>
          <a-form-item label="商品分类">
            <!-- <a-select style="width: 180px" 
              v-decorator="[
                'goodsClassificationId',
              ]" :allowClear="true" placeholder="请选择" :options="productClassifyList"></a-select> -->
            <a-tree-select
              allowClear
              style="width:180px"
              :replaceFields="{children:'children', title:'classifyName', key:'id', value: 'id' }"
              v-decorator="[
                'goodsClassificationId',
              ]"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="productClassifyList"
              placeholder="请选择"
              tree-default-expand-all
              >
              <span slot="title" slot-scope="{ value }">
                  {{ value }}
              </span>
            </a-tree-select>
          </a-form-item>
          <!-- <a-form-item label="商品品牌">
            <a-select style="width: 180px"
              v-decorator="[
                'goodsBrandId',
              ]" :allowClear="true" placeholder="请选择" :options="productNameList"></a-select>
          </a-form-item> -->
          <a-form-item label="商品类目">
            <!-- <a-select style="width: 180px"
              v-decorator="[
                'goodsCategoryId',
              ]" :allowClear="true" placeholder="请选择" :options="productCategoryList"></a-select> -->
              <a-tree-select
                allowClear
                style="width:180px"
                :replaceFields="{children:'children', title:'categoryName', key:'id', value: 'id' }"
                v-decorator="[
                  'goodsCategoryId',
                ]"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="productCategoryList"
                placeholder="请选择"
                tree-default-expand-all
                >
                <span slot="title" slot-scope="{ value }">
                    {{ value }}
                </span>
            </a-tree-select>
          </a-form-item>
          <a-form-item label="商品状态">
            <a-select style="width: 180px"
              v-decorator="[
                'goodsStatus',
              ]" :allowClear="true" placeholder="全部" :options="goodsStatusList"></a-select>
          </a-form-item>
          <a-form-item label="商品分组">
            <!-- <a-select style="width: 180px"
              v-decorator="[
                'goodsGroupId',
              ]" :allowClear="true" placeholder="请选择" :options="productGroupList"></a-select> -->
            <a-tree-select
                allowClear
                style="width:180px"
                :replaceFields="{children:'children', title:'groupName', key:'id', value: 'id' }"
                v-decorator="[
                  'goodsGroupId',
                ]"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="productGroupList"
                placeholder="请选择"
                tree-default-expand-all
                >
                <span slot="title" slot-scope="{ value }">
                    {{ value }}
                </span>
            </a-tree-select>
          </a-form-item>
          <a-form-item label="商品所属">
            <a-select style="width: 180px"
              v-decorator="[
                'goodsAscription',
              ]" :allowClear="true" placeholder="全部" :options="goodsAscriptionList"></a-select>
          </a-form-item>

          <a-form-item label="商品erp编码">
            <a-input
              style="width: 200px"
              v-decorator="['erpCode']"
              placeholder="请输入商品erp编码"
              autocomplete="off"
            >
            </a-input>
          </a-form-item>
        </a-form>
      </template>
      <template slot="oprationRow">
        <permission authority="goods:add">
          <a-button type="primary" icon="plus" @click="newProduct()">添加商品</a-button>
        </permission>
        <!-- <permission>
          <a-button @click="selectAll()">当页全选</a-button>
        </permission> -->
        <permission authority="goods:update">
          <a-button @click="onShelf($refs.searchtable.selectedRowKeys)">上架</a-button>
        </permission>
        <permission authority="goods:update">
          <a-button @click="offShelf($refs.searchtable.selectedRowKeys)">下架</a-button>
        </permission>
        <permission authority="goods:delete">
          <a-button @click="deleteRows($refs.searchtable.selectedRowKeys)">删除</a-button>
        </permission>
        <permission authority="goods:update">
          <a-button @click="changeGroup($refs.searchtable.selectedRowKeys)">更换分组</a-button>
        </permission>

        <!-- <permission>
          <a-button @click="addProductGroup">添加商品分组</a-button>
          <a-button @click="listProductGroup">查询商品分组</a-button>
        </permission>
        <permission>
          <a-button @click="addProductClassify">添加商品分类</a-button>
          <a-button @click="listProductClassify">查询商品分类</a-button>
        </permission> -->
      </template>
      <template slot="tableOperation" slot-scope="{record}">
        <a-space>
          <permission authority="goods:modify">
            <a href="javascript:;" class="text-primary pointer" @click="newProduct(record.id,'update')">编辑</a>
          </permission>
          <permission  authority="goods:delete" v-if="record.goodsStatus!=2">
            <a href="javascript:;" class="text-primary text-danger" @click="deleteRows([record.id])">删除</a>
          </permission>
          <permission  authority="goods:update">
            <a href="javascript:;" class="text-primary text-danger" @click="offShelf([record.id])" v-if="record.goodsStatus==2">下架</a>
            <template v-if="(record.goodsStatus==1 || record.goodsStatus==3) && record.goodsStatus==2">
            /
            </template>
            <a href="javascript:;" class="text-primary text-danger" @click="onShelf([record.id])" v-if="record.goodsStatus==1 || record.goodsStatus==3">上架</a>
          </permission>
          <permission >
            <a href="javascript:;" class="text-primary pointer" @click="handlePreview(record.id)">预览</a>
          </permission>
          <permission v-if="record.goodsStatus==2">
            <a href="javascript:;" class="text-primary pointer" @click="handlePromotion(record.id, record.goodsName)">推广</a>
          </permission>
          <template v-if="userInfo.userIdType ==4">
            <a href="javascript:;" class="text-primary pointer" @click="distribute(record.id)">分销</a>
          </template>
           <permission authority="goods:modify">
            <a href="javascript:;" class="text-primary pointer" @click="newProduct(record.id,'copy')">复制</a>
          </permission>
        </a-space>
      </template>
    </search-table>
    <Extension :visible="showGoodsQrc"
               :id="showGoodsQId"
               @cancel="showGoodsQrc = false"
               @submit="showGoodsQrc = false"
    ></Extension>
    <product-group :visible="show" @cancel="handleCancel" @submit="handleSubmit"></product-group>
    <ProductPreview :data="formData" :visible="previewShow" @cancel="previewShow = false"></ProductPreview>
    <ProductCode :data="promotionData" :visible="promotionShow" @cancel="promotionShow = false"></ProductCode>
  </div>
</template>
<script>
import ProductGroup from '../commodityLibrary/components/ProductGroup';
import SearchTable from './components/SearchTable'
import ProductCode from './components/ProductCode'
import ProductPreview from '../commodityLibrary/components/ProductPreview';
import Extension from "./components/Extension";
export default {
  name: 'CommodityManage',
  components:{
    ProductGroup,
    ProductPreview,
    ProductCode,
    Extension,
    SearchTable
  },
  data(){
    return {

      pagination: {
        showQuickJumper: true,
        total: 0,
        current: null,
        pageSize: 10,
        showTotal: (total) => `共${ total }条`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100', '200']
      },

      url:'/goods/page',
      productCategoryList:[],
      form: this.$form.createForm(this, { name: 'table_search' }),
    // selectKeys:[],//
      productClassifyList:[],//商品类型
      productGroupList:[],//商品分组
      goodsAscriptionList:[
        {
          label:'本店商品',
          value:1
        },{
          label:'总店商品',
          value:2
        }
      ],
      goodsStatusList:[
        {
          label:'仓库中',
          value:1
        },{
          label:'上架',
          value:2
        },{
          label:'已下架',
          value:3
        },
      ],
      columns: [
        {
          title: '商品名称',
          dataIndex: 'goodsName',
          key: 'goodsName',
          //align: 'center',
          customRender: (text, row) => {
            return <div class="product_td"><table-img src={row.goodsPicture}/><div class="product_name">{text}</div></div>
          }
        },
        {
          title: '价格',
          dataIndex: 'salePrice',
          key: 'salePrice',
          customRender:(text,row)=>{
            let res = ''
            if(row.paymentWay==0 || row.paymentWay==1 || row.paymentWay == null) {
              res = text ? `¥ ${(+text / 100).toFixed(2)}` : '¥ 0.00'
            } else if(row.paymentWay==2) {
              res = (text ? `¥ ${(+text / 100).toFixed(2)}` : '¥ 0.00')+'+'+row.integralPrice+'固定积分'
            } else if(row.paymentWay==3) {
              res = row.integralPrice+'积分'
            }
            return res;
          }
        },
        {
          title: '总可售库存',
          dataIndex: 'goodsInventoryTotal',
          key: 'goodsInventoryTotal'
        },
        {
          title: '销量',
          dataIndex: 'realSales',
          key: 'realSales'
        },
        {
          title: '状态',
          dataIndex: 'goodsStatus',
          key: 'goodsStatus',
          customRender:(text,row)=>{            
            return (this.getStatusLabelByStatusValue(text) || {}).label;
          }
        },
        {
          title: '商品分类',
          dataIndex: 'goodsClassificationName',
          key: 'goodsClassificationName'
        },
        {
          title: '创建时间',
          dataIndex: 'createDate',
          key: 'createDate'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        },
      ],
      show:false,
      ids:[],
      productList:[],
      previewShow:false,
      formData:{},
      // 分销model
      showGoodsQrc: false,
      showGoodsQId:'',
      // 推广弹窗控制
      promotionShow: false,
      promotionData: {
        url: '',
        name: ''
      }
    }
  },
  computed:{
    userInfo(){
      return this.$store.getters.userInfo || {};
    }
  },
  created(){
    this.getProductClassify();//分类
    this.getProductGroup();//分组
    this.getProductCategory();//类目

    this.getProductList();

    console.log('this.getStatusLabelByStatusValue',this.getStatusLabelByStatusValue(2));

    if (this.$route.query.current){
      console.log(this.$route.query.current)
      this.pagination.current = this.$route.query.current
    }else {
      this.pagination.current =  1
    }
  },
  methods:{
    //获取商品数据，为删除准备
    async getProductList(){
      let res=await this.$get('/goods/page',{
        goodsName:this.form.getFieldValue('goodsName'),
        goodsClassificationId: this.form.getFieldValue('goodsClassificationId'),
        goodsCategoryId: this.form.getFieldValue('goodsCategoryId'),
        goodsStatus: this.form.getFieldValue('goodsStatus'),
        goodsGroupId: this.form.getFieldValue('goodsGroupId'),
        goodsAscription: this.form.getFieldValue('goodsAscription')
      },false,true);
      if(res && res.returnCode=='1000'){
        this.productList=(res.dataInfo || {}).records || [];
        console.log('=============this.productList============',this.productList)
      }
      else{ 
        this.productList=[];
      }
    },
    getStatusLabelByStatusValue(value){
      return this.goodsStatusList.find(item=>{
        return item.value==value;
      })
    },
    //商品分类
    async getProductClassify(){
      let res=await this.$get('/goods/classify/tree',{
        shopId:this.userInfo.shopId || ''
      });
      if(res && res.returnCode=='1000'){
        this.productClassifyList=res.dataInfo || [];
      }
      else {
        this.productClassifyList=[];
      }
    },
    //商品分组
    async getProductGroup(){
      let res=await this.$get('/goods/group/tree',{
        shopId:this.userInfo.shopId || ''
      },false,true);
      if(res && res.returnCode=='1000'){
        this.productGroupList=res.dataInfo || [];
      }
      else {
        this.productGroupList=[];
      }
    },
    //商品类目
    async getProductCategory(){
      let res=await this.$get('/goods/category/tree',{
        categoryStatus:1
      },false,true);
      if(res && res.returnCode=='1000'){
        this.productCategoryList=res.dataInfo || [];
      }
      else {
        this.productCategoryList=[];
      }
    },
    //上架
    onShelf(ids){
      console.log('上架',ids)
      this.onOffShelf(ids,2)
    },
    //下架
    offShelf(ids){
      console.log('下架',ids)
      this.onOffShelf(ids,3)
    },
    //商品操作（2:上架,3:下架）
    onOffShelf(ids,status){
      if(ids.length==0){
        return this.$message.warn('请先选择一项后再进行操作');
      }
      this.$post('/goods/status/shelves',{
        goodsIdList:ids,
        goodsOperation:status,
      }).then(res=>{
        if(res && res.returnCode=='1000'){
          this.$refs.searchtable.refreshTable();  
          let statusText=status==2?'上架成功':'下架成功';        
          return this.$message.success(statusText);
        }
        else {
          let statusText=status==2?'上架失败':'下架失败'; 
          return this.$message.error(statusText)
        }
      })
    },
    //新增/编辑商品
    newProduct(id,opration){
      let params={};
      if(id){//修改
        params={
          id,
          current:this.pagination.current,
          opration:opration,
        };
      }
      this.$router.push({
        name:'ProductCommodityManageCommodityManageAddEditProduct',
        query:params
      })
    },
    //删除
    async deleteRows(ids){
      await this.getProductList();
      console.log('this.productList',this.productList)
      let shelvesIds=[];
      for(let i=0;i<this.productList.length;i++){
        let item=this.productList[i];
        console.log(item.id);
        if(item.goodsStatus==2){
          shelvesIds.push(item.id);
        }
      }
      console.log(shelvesIds,ids)
      for(let i=0;i<ids.length;i++){
        if(shelvesIds.includes(ids[i])){
          return this.$message.error('删除项存在上架商品，请重新选择后操作！')
        }
      }
      if (!ids || ids.length === 0) return this.$message.warn('请先选择一项后再进行操作')
      this.$confirm({
        title: '删除提示',
        content: '删除操作不可恢复，请确认是否删除？',
        okText: '确认删除',
        cancelText: '取消',
        onOk: () => {
          this.$post('/goods/delete', { goodsIdList:ids }).then(res => {
            if (res && res.returnCode == 1000) {
              this.$message.success('删除成功')
              this.$refs.searchtable.refreshTable()
            }
          })
        }
      })
    },
    //获取商品信息
    async getProductInfo(id){
        let res=await this.$get('/goods/query',{
            id 
        });
        if(res && res.returnCode=='1000'){
          if(res.dataInfo.goodsSpecList && res.dataInfo.goodsSpecList.length>0){
            res.dataInfo.goodsSpecList[0].salePrice=(res.dataInfo.goodsSpecList[0].salePrice/100).toFixed(2);
            res.dataInfo.goodsSpecList[0].marketPrice=(res.dataInfo.goodsSpecList[0].marketPrice/100).toFixed(2);
          }
          this.formData=res.dataInfo||{};
        }
    },
    //预览
    async handlePreview(id){
      await this.getProductInfo(id);
      this.previewShow=true;
    },
    //获取商品推广码
    async getProductCode(id, name){
      let res=await this.$get('/goods/qrcode',{
        id
      });
      if(res && res.returnCode=='1000'){
        this.promotionData = {
          url: res.dataInfo,
          name
        }
      }
    },
    // 推广
    async handlePromotion(id, name) {
      await this.getProductCode(id, name);
      this.promotionShow = true;
    },
    distribute(record) {
      this.showGoodsQId = record;
      this.showGoodsQrc = true;
    },
    //更换分组
    async changeGroup(ids){
      if(ids.length==0){
        return this.$message.warn('请先选择一项后再进行操作');
      }
      console.log(ids);
      //this.$refs.searchtable.refreshTable();
      this.ids=ids;
      this.show=true;
    },
    handleCancel(){
      this.show=false;
    },
    async handleSubmit(groupId){
      this.show=false;
      let params={
        goodsIdList:this.ids,
        goodsGroupId:groupId,//商品分组id
      };
      console.log(params);
      let res=await this.$post('/goods/change/group',params)
      this.ids=[];
      if(res && res.returnCode=='1000'){
        this.$refs.searchtable.refreshTable();
        this.$message.success('更换分组成功');
      }
      else {
        this.$message.error('更换分组失败')
      }
    },

  }
}
</script>

<style lang="less" scoped>
.product_td{
  display: flex;
  align-items: center;
  .product_name{
    margin-left:6px;
  }
}
</style>

